package com.aaa.vegetablemarketexpress.service.impl;

import com.aaa.vegetablemarketexpress.dao.ProductDao;
import com.aaa.vegetablemarketexpress.entity.Product;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.ProductService;
import com.aaa.vegetablemarketexpress.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @FileName: ProductServiceImpl
 * @Description:
 * @Author: qxh
 * @CreateTime: 2025/9/5 20:01
 * @Version: 1.0.0
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductDao productDao;
    @Resource
    private HttpSession session; // 获取登录信息

/*    // 注入商品图片路径配置
    @Value("${file.upload.image-url-path}")
    private String productImagePath;

    @Value("${file.access.prefix}")
    private String fileAccessPrefix;*/

//    /**
//     * 根据id查询商品信息
//     * @param productId
//     * @return
//     */
//    @Override
//    public Product selectProductById(Long productId) {
//        return productDao.selectProductById(productId);
//    }
@Override
public Product selectProductById(Long productId) {
    return productDao.selectProductById(productId);
}

    /**
     * 查询商品列表,分页
     * @param page
     * @return
     */
    @Override
    public PageInfo selectProductList(Page<Product> page) {
        Integer pageNo = page.getPageNo();
        Integer pageSize = page.getPageSize();
        //判断pageNo，pageSize
        if (pageNo == null || pageNo == 0|| pageSize == null || pageSize == 0){
            //直接抛出异常
            throw new RuntimeException("参数异常");

        }
        PageHelper.startPage(pageNo,pageSize);
        Product data = page.getData();
        return PageInfo.of(productDao.selectProductList(data));
    }
    /**
     * 添加商品
     * @param product
     * @return
     */
    @Override
    public int insertProduct(Product product) {
        product.setStatus("0");
        product.setDelFlag("0");
        product.setCreateTime(new Date());
        User userList = (User)session.getAttribute("userInfo");
        String userName = userList.getUserName();
        product.setCreateBy(userName);
        return productDao.insertProduct(product);
    }
    /**
     * 修改商品
     * @param product
     * @return
     */
    @Override
    public int updateProduct(Product product) {
        product.setUpdateTime(new Date());
        User userList = (User)session.getAttribute("userInfo");
        String userName = userList.getUserName();
        product.setUpdateBy(userName);
        return productDao.updateProduct(product);
    }
    /**
     * 删除商品
     * @param productId
     * @return
     */
    @Override
    public int deleteProductById(Long productId) {
        return productDao.deleteProductById(productId);
    }

    /**
     * 上传商品图片
     * @param file 图片文件
     * @return 图片访问URL
     */
/*    @Override
    public String uploadProductImage(MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }

        // 验证文件类型（只允许jpg和png）
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
            throw new RuntimeException("文件类型不支持，仅支持jpg/png格式");
        }

        // 验证文件大小（不超过5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            throw new RuntimeException("文件大小超过限制，最大支持5MB");
        }

        // 获取项目根路径并构建保存路径
        String projectPath = System.getProperty("user.dir");
        String fullPath = projectPath + "/" + productImagePath;

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String prefix = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "_" +
                UUID.randomUUID().toString().substring(0, 8);
        String uniqueFileName = prefix + suffix;

        try {
            // 创建目录（如果不存在）
            Path path = Paths.get(fullPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            // 保存文件
            Path filePath = Paths.get(fullPath + uniqueFileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回访问URL
            return fileAccessPrefix + "imageUrl/" + uniqueFileName;
        } catch (Exception e) {
            throw new RuntimeException("文件保存失败: " + e.getMessage());
        }
    }*/

}
